package org.porridge.prdblog.article.business;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.db.createsql.AbstrDao;
import org.porridge.module.fun.po.Fun;
import org.porridge.module.main.po.User;
import org.porridge.prdblog.article.dao.ArticleDao;
import org.porridge.prdblog.article.po.Article;
import org.porridge.prdblog.article.po.FtlPo;
import org.porridge.prdblog.label.po.Label;
import org.porridge.prdblog.label.po.LabelArt;
import org.porridge.prdblog.link.po.Link;
import org.porridge.util.Constant;
import org.porridge.util.FrameworkUtil;
import org.transmit.ActionContext;

import com.sun.org.apache.regexp.internal.recompile;

/**
 * 静态页面生成专用Business
* @Title: FrameworkBusiness.java 
* @Package org.porridge.prdblog.article.business 
* @Description: TODO 
* @author porridge
* @url  http://www.prdblog.com/
* @email  mfkwfc@gmail.com   
* @date 2014年4月26日 下午3:02:30 
* @version V1.0
 */
public class FrameworkBusiness  extends AbstrDao<ArticleDao>{
	/**
	 * 重新生成静态页面
	 * 全部页面
	 * @return
	 * @throws Exception 
	 */
	public boolean RefreshCreateHtml() throws Exception{
		FrameworkUtil.deleHtml();
		List<Article> arts=this.absDao.getList(Article.class,"*","labletype='1'","top desc,sendtime","desc",0,99999);
		List<Fun> funs=this.absDao.getList(Fun.class,"*","type='3'","sort","asc",0,99999);
		List<LabelArt> labs=findLabels();
		createNavbar(funs);//生成顶部导航
		createRight(funs,labs);
		
		for(Fun fun:funs){
			if(fun.getFtlpath()!=null && fun.getFtlpath().trim().length()>0){
				if("index".equals(fun.getId()))
					createList(arts,funs,labs,fun.getFtlpath(),"html"+"/"+fun.getId(),"最新发布");
				else if("3".equals(fun.getType()) && "2".equals(fun.getFtltype()))//列表
					createList(findArticleFun(arts,fun.getFuncode()),funs,labs,fun.getFtlpath(),"html"+"/list/"+fun.getFuncode(),fun.getName());
				else if("3".equals(fun.getType()) && "1".equals(fun.getFtltype())){//单页
					List<Article> oneart=this.absDao.getList(Article.class,"*","cls='"+fun.getFuncode()+"'");
					if(oneart.size()>0){
						Article at=oneart.get(0);
						at.setId(at.getCls());
						createArticle(at,fun.getFtlpath(),funs,labs,"/html/list",null,null);
					}
				}
			}
		}
		return true;
	}
	/**
	 * 过滤查询
	 * @return
	 */
	public List<Article> findArticleFun(List<Article> arts,String code){
		List<Article> teart=new ArrayList<Article>();
		for(Article at:arts){
			if(code.equals(at.getCls())){
				teart.add(at);
			}
		}
		return teart;
	}
	/**
	 * 生成list
	 * @param arts
	 * @param funs
	 * @param labs
	 * @param fun
	 * @param writeurl
	 * @param name
	 * @return
	 */
	public boolean createList(List<Article> arts,List<Fun> funs,List<LabelArt> labs,String ftlpath,String writeurl,String topname){
		int pagesize=10;//每页默认条数
		int pagenum=0;//总页数
		Map<String,Object> map1=new HashMap<String,Object>();//每页存放的变量
		List<Article> temparts=null;//临时变量,存放每页数据
		
		
		if(Constant.SETTING.getPage_size()!=null && Constant.SETTING.getPage_size().matches("\\d*"))
			pagesize=Integer.valueOf(Constant.SETTING.getPage_size());
		pagenum=Integer.valueOf(arts.size()/pagesize);
		if(arts.size()%pagesize!=0 || arts.size()==0)
			++pagenum;
		String projname=ActionContext.getRequest().getContextPath();
		for(int j=0;j<pagenum;j++){
			map1.put("thpage",j+1);//当前页
			map1.put("sumpage",pagenum);//总页数
			map1.put("funs",funs);
			map1.put("labs",labs);
			map1.put("pageurl",writeurl);
			map1.put("topname",topname);
			//组装页面
			StringBuffer pagea=new StringBuffer();
			
			int start=1;
			if(j-5>0){
				pagea.append("<a href=\""+projname+"/"+writeurl+".html\">1</a><span>...</span>");
				start=j-5;
			}
			if(start+10>pagenum && pagenum>10)
				start-=(start+9-pagenum);
			int endpage=start+10;
			if(endpage>pagenum)
				endpage=pagenum;
			
			String t1="";
			if(endpage!=1){//如果只有一页就没必要显示页码了
				for(int step=start;step<=endpage;step++){
					if((j+1)==step)
						t1="class=\"active\"";
					else
						t1=" href=\""+projname+"/"+writeurl+(step!=1?step:"")+".html\"";
					pagea.append("<a "+t1+">"+step+"</a>");
				}
			}
			if(j+5<pagenum){
				pagea.append("<span>...</span><a href=\""+projname+"/"+writeurl+pagenum+".html\">"+pagenum+"</a>");
			}
			map1.put("pagea",pagea);
			
			temparts=new ArrayList<Article>();
			for(int i=j*pagesize;i<j*pagesize+pagesize;i++){
				if(i<arts.size()){
					temparts.add(arts.get(i));
					Article next=(i+1==arts.size()?null:arts.get(i+1));
					createArticle(arts.get(i),"one.ftl",funs,labs,writeurl,(i!=0?arts.get(i-1):null),next);
				}
			}
			map1.put("arts",temparts);//数据集合
			
			FrameworkUtil.createFtl(map1,ftlpath,writeurl+(j==0?"":(j+1))+".html");
			FrameworkUtil.createFtl(map1,ftlpath.replace(".ftl","_pjax.ftl"),writeurl+(j==0?"":(j+1))+"_pjax.html");
		}
		return true;
	}
	/**
	 * 生成单页文章
	 * @param art  单个文章
	 * @param funs 功能集合
	 * @param labs 标签集合
	 * @param writeurl  生成地址
	 * @param prev  上一个
	 * @param next  下一个
	 */
	public void createArticle(Article art,String ftlpath,List<Fun> funs,List<LabelArt> labs,String writeurl,Article prev,Article next){
		Map<String,Object> map1=new HashMap<String,Object>();
		map1.put("art",art);
		map1.put("funs",funs);
		map1.put("labs",labs);
		map1.put("writeurl",writeurl);
		map1.put("prev",prev);
		map1.put("next",next);
		FrameworkUtil.createFtl(map1,ftlpath,writeurl+"/"+art.getId()+".html");
		FrameworkUtil.createFtl(map1,ftlpath.replace(".ftl","_pjax.ftl"),writeurl+"/"+art.getId()+"_pjax.html");
	}
	/**
	 * 查询表的关联关系
	 * @return
	 * @throws SQLException
	 */
	private List<LabelArt> findLabels() throws SQLException{
		ResultSet rs=this.absDao.findQuery("SELECT id,aid,(SELECT NAME FROM prd_label l WHERE l.id=p.lid LIMIT 0,1) AS 'name' FROM prd_labelart p");
		List<LabelArt> labs=new ArrayList<LabelArt>();
		while(rs.next()){
			LabelArt art=new LabelArt();
			art.setId(rs.getString("id"));
			art.setAid(rs.getString("aid"));//文章id
			art.setLid(rs.getString("name"));//指标签id.不过我是通过自定义sql语句查询的存放的是标签名称
			labs.add(art);
		}
		rs.close();
		return labs;
	}
	/**
	 * 生成导航
	 * @return
	 * @throws Exception 
	 */
	public boolean createNavbar(List<Fun> funs) throws Exception{
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("funs",funs);
		String url="WEB-INF"+File.separatorChar+"classes"+File.separator+"prdftl"+File.separatorChar+"loadbase"+File.separator+"navbar.ftl";
		return FrameworkUtil.createFtl(map,"base/navbar.ftl",url);
	}
	/**
	 * 生成右边的栏目数据
	 * @return
	 * @throws Exception 
	 */
	public boolean createRight(List<Fun> funs,List<LabelArt> labs) throws Exception{
		String url="WEB-INF"+File.separatorChar+"classes"+File.separator+"prdftl"+File.separatorChar+"loadbase"+File.separator+"right.ftl";
		Map<String,Object> map=new HashMap<String, Object>();
		//查询标签分类
		String sql="SELECT funcode,(SELECT id FROM sys_fun t WHERE t.funcode=s.funcode) AS 'funid',(SELECT NAME FROM sys_fun t WHERE t.funcode=s.funcode) AS 'name',(SELECT COUNT(1) FROM prd_article WHERE cls=funcode) AS 'number' FROM sys_fun s WHERE TYPE='3' AND ftltype='2' GROUP BY funcode HAVING number!='0'";
		ResultSet rs=this.absDao.findQuery(sql);
		List<FtlPo> fts=new ArrayList<FtlPo>();
		while(rs.next()){
			FtlPo ft=new FtlPo();
			ft.setName(rs.getString("name"));
			ft.setNumber(rs.getString("number"));
			ft.setLink("/html/list/"+rs.getString("funcode")+".html");
			fts.add(ft);
		}
		map.put("fts",fts);
		//查询文章归档
		sql="SELECT LEFT(sendtime,7) AS 'name',COUNT(1) AS 'number' FROM (SELECT funcode FROM sys_fun WHERE TYPE='3' AND ftltype='2') a LEFT JOIN prd_article ON funcode=cls GROUP BY LEFT(sendtime,7) order by LEFT(sendtime,7) desc";
		rs=this.absDao.findQuery(sql);
		List<FtlPo> ftstime=new ArrayList<FtlPo>();
		String projname=ActionContext.getRequest().getContextPath();
		String firstdate="";
		while(rs.next()){
			FtlPo ft=new FtlPo();
			ft.setName(rs.getString("name"));
			ft.setNumber(rs.getString("number"));
			ft.setLink(projname+"/html/timegroup/"+ft.getName()+".html");
			ftstime.add(ft);
			List<Article> arts=this.absDao.getList(Article.class,"*","sendtime LIKE '"+ft.getName()+"%' AND cls IN(SELECT funcode FROM sys_fun WHERE TYPE='3' AND ftltype='2')","sendtime","desc");
			createList(arts,funs,labs,"index.ftl","html/timegroup/"+ft.getName(),"时间归档:"+ft.getName());//生成归档
			if(firstdate==null && ft.getName()!=null && ft.getName().length()>4)firstdate=ft.getName().substring(0,4);
		}
		map.put("firstdate",firstdate);
		if(ftstime.size()>0)
			map.put("ftstimejson",JSONArray.fromObject(ftstime).toString());
		else
			map.put("ftstimejson","");
		
		//查询标签云
		sql="SELECT * FROM (SELECT id,name,(SELECT COUNT(1) FROM prd_labelart l WHERE l.lid=p.id AND aid IN(SELECT id FROM prd_article WHERE cls IN(SELECT funcode FROM sys_fun WHERE TYPE='3' AND ftltype='2'))) AS 'number'  FROM prd_label p ) a WHERE number!='0'";
		rs=this.absDao.findQuery(sql);
		List<FtlPo> ftslable=new ArrayList<FtlPo>();
		while(rs.next()){
			FtlPo ft=new FtlPo();
			ft.setName(rs.getString("name"));
			ft.setNumber(rs.getString("number"));
			ft.setLink("/html/labelgroup/"+ft.getName()+".html");
			ftslable.add(ft);
			List<Article> arts=this.absDao.getList(Article.class,"*","id in(SELECT aid FROM prd_labelart WHERE lid='"+rs.getString("id")+"') AND cls IN(SELECT funcode FROM sys_fun WHERE TYPE='3' AND ftltype='2')","sendtime","desc");
			createList(arts,funs,labs,"index.ftl","html/labelgroup/"+ft.getName(),"标签:"+ft.getName());//生成归档
		}
		map.put("ftslable",ftslable);
		rs.close();
		
		List<Link> links=this.absDao.getList(Link.class,"*","1=1","name","asc");
		map.put("links",links);
		
		return FrameworkUtil.createFtl(map,"base/right.ftl",url);
	}
}
